package org.tinygame.herostory.cmdHandler;

import io.netty.channel.ChannelHandlerContext;
import org.tinygame.herostory.model.MoveState;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

/**
 * @author shkstart
 * @create 2022-05-05 10:17
 */
public class WhoElseIsHereCmdHandler implements ICmdHandler<GameMsgProtocol.WhoElseIsHereCmd>{
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.WhoElseIsHereCmd cmd) {
        if(null==ctx || null==cmd){
            return;
        }

        //构建一个who在场的结果消息
        GameMsgProtocol.WhoElseIsHereResult.Builder resultBuilder=GameMsgProtocol.WhoElseIsHereResult.newBuilder();

        //将字典中的用户依次取出，构建多个userInfoBuilder，全部放入resultBuilder
        for(User currUser: UserManager.listUser()){
            if(null==currUser){
                continue;
            }
            //构建userInfoBuilder，里面包含userId、heroAvatar以及mvStateBuilder
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.Builder userInfoBuilder=GameMsgProtocol.WhoElseIsHereResult.UserInfo.newBuilder();
            userInfoBuilder.setUserId(currUser.userId);
            userInfoBuilder.setHeroAvatar(currUser.heroAvatar);

            //构建mvStateBuilder，完成移动状态赋值
            //MoveState mvState= currUser.moveState;
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.Builder mvStateBuilder=
                    GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.newBuilder();
            mvStateBuilder.setFromPosX(currUser.moveState.fromPosX);
            mvStateBuilder.setFromPosY(currUser.moveState.fromPosY);
            mvStateBuilder.setToPosX(currUser.moveState.toPosX);
            mvStateBuilder.setToPosY(currUser.moveState.toPosY);
            mvStateBuilder.setStartTime(currUser.moveState.startTime);

            //将mvStateBuilder放入到userInfoBuilder中
            userInfoBuilder.setMoveState(mvStateBuilder);


            resultBuilder.addUserInfo(userInfoBuilder);
        }
        //构建结果并发送
        GameMsgProtocol.WhoElseIsHereResult newResult=resultBuilder.build();
        ctx.writeAndFlush(newResult);
    }
}
